package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @DESCRIPTION: 登录控制器
 * @author: zr
 * @DATE: 2023/1/14 20:57
 */
@Controller
public class LoginController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("login.html")
    public String loginPage(@RequestParam("redirect_url") String redirectUrl, Model model,
                            @CookieValue(value = "sso_token", required = false) String ssoToken) {
        model.addAttribute("url", redirectUrl);
        if (!StringUtils.isEmpty(ssoToken)) {
            // 说明之前有人登录过了   浏览器留下了痕迹
            return "redirect:" + redirectUrl + "?token=" + ssoToken;
        }
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(String username, String password, String url, HttpServletResponse response) {
        // 登录成功
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            // 重定向时  去到页面  发现又没登录 死循环了
            // 将登录成功的用户存起来
            String uuid = UUID.randomUUID().toString().replace("_", "");
            stringRedisTemplate.opsForValue().set(uuid, username);
            // 给浏览器留下登录过的痕迹
            Cookie cookie = new Cookie("sso_token", uuid);
            response.addCookie(cookie);
            return "redirect:" + url + "?token=" + uuid;
        }
        return "login";
    }

    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token) {
        String userInfo = stringRedisTemplate.opsForValue().get(token);
        return userInfo;
    }
}
